const RA = (function () {
    //更新侧边栏数据的函数
    function updateAside() {
        //获取被选中的元素
        let selected = $('.aside-goodsList').find('.aside-goodsItem input:checked').parents('.aside-goodsItem');
        let choseNum = 0;
        let sumPrice = 0;
        [...selected].forEach(function (el) {
            choseNum += Math.abs(parseInt($(el).find('.goodsNum').text()));
            sumPrice += Math.abs(parseInt($(el).find('.goodsNum').text())) * parseFloat($(el).find('.goodsPrice em').text());
        })
        //数量绑定
        $('aside').find('.selectNum').text(choseNum);
        // 总价绑定
        $('aside').find('.sumPrice').text(sumPrice.toFixed(2));

        //单选和全选的绑定
        //获取全部checkbox数量
        let sumNum = $('.aside-goodsList').find('input[type="checkbox"]').length;
        // 获取被选中的CheckBox数量
        let selectNum = selected.length;
        if (sumNum !== 0) {
            $('#selectAll').prop('checked', sumNum === selectNum);
        }
    }

    /**
     * 侧边栏数据渲染
     */
    function renderAside() {
        //获取用户数据
        let userObj = JSON.parse(localStorage.getItem('userInfo') || '{}');
        //判断用户是否登录,如果未登录则跳转到登录界面
        if (!userObj.u_id) {//如果没登录就切换到登录
            layer.msg('请您先登录');
            setTimeout(function () {
                location.href = 'login.html';
            }, 1000);
            return;
        }

        //开始渲染数据
        $.ajax({
            url: './cart/query',
            type: 'get',
            data: {uId: userObj.u_id}
        }).then(function (res) {
            if (res.status === 200) {
                //获取购物车的商品列表
                let goodList = res.data;
                //向侧边栏购物车中添加内容
                let strHtml = ``
                goodList.forEach(function (el) {
                    let checked = "";
                    if (el.c_desc === '1') {
                        checked = "checked";
                    }
                    strHtml += `<li class="aside-goodsItem clearFix" data-cid="${el.c_id}">
                    <input type="checkbox" ${checked}>
                    <div class="goodsImg fl">
                        <img src="${el.c_img}" alt="">
                    </div>
                    <div class="goodsMsg fl">
                        <h3>
                            ${el.c_name}
                        </h3>
                        <div class="goodsPrice clearFix">
                            <span class="fl">￥<em>${el.c_price}</em></span>
                            <i class="goodsNum fr">${el.c_num}</i>
                        </div>
                    </div>
                    <a href="javascript:" class="aside-delete a-hover">
                    <i class="iconfont icon-laji"></i>
                    </a>
                </li>`
                });
                $('.aside-goodsList').html(strHtml);

                //改变购物车标记的数量
                $('.shopCar-num').text(goodList.length);
                if (goodList.length >= 1) {
                    $('.noReplace').hide();
                } else {
                    $('.noReplace').show();
                }

                //更新前台数据
                updateAside();
            }
        });
    }


    //没有商品的情况
    function blankReplace() {
        let goodsClassNum = $('.myCarBox').find('.goods-car li').length;
        if (goodsClassNum <= 0) {
            $('.myCarBox').parent().hide();
            $('.blankReplace').show();
        } else {
            $('.myCarBox').parent().show();
            $('.blankReplace').hide();
        }
    }
    
    //减符号禁用的方法
    function reduceDisabled() {
        let goodNum = $('.goods-car .goodsNum');
        [...goodNum].forEach(function (el) {
            if (Math.abs($(el).val()) > 1) {
                $(el).prev().removeClass('disabled');
            } else {
                $(el).prev().addClass('disabled');
            }
        });
    }

    //更新购物车数据的函数
    function update() {
        //初始化商品的种类数量
        $('.classNum').text($('.goods-car li').length);
        if (!$('.goods-car li').length) {
            blankReplace();
            return;
        }

        //获取被选中的商品
        let selected = $('.myCarBox').find('.goods .selectItem:checked').parents('.goods');

        let sumNum = 0;
        let realMoney = 0;
        [...selected].forEach(function (el) {
            sumNum += Math.abs(parseInt($(el).find('.goodsNum').val()));
            realMoney += parseFloat($(el).find('.sumPrice em').text())
        })
        //统计选中的商品数量
        $('.chooseGoodsNum').text(sumNum);
        //统计选中商品的总金额
        $('.realMoney').text(realMoney.toFixed(2));
        //统计最终金额
        let discount = parseFloat($('.couponsBackCashAmount').text())
        $('.sumRealMoney').text((realMoney - discount).toFixed(2));

        //单选和全选的绑定
        // 选中的多选框数量
        let selectItemNum = $('.myCarBox').find('.goods .selectItem:checked').length;
        //多选框的总数量
        let selectItemAllNum = $('.myCarBox').find('.goods .selectItem').length;
        [...$('.myCarBox').find('.selectAll')].forEach(function (el) {
            $(el).prop('checked', selectItemNum === selectItemAllNum);
        });
    }

    /**
     * 购物车数据渲染
     */
    function render() {
        //获取用户数据
        let userObj = JSON.parse(localStorage.getItem('userInfo') || '{}');
        //判断用户是否登录,如果未登录则跳转到登录界面
        if (!userObj.u_id) {//如果没登录就切换到登录
            layer.msg('请您先登录');
            setTimeout(function () {
                location.href = 'login.html';
            }, 1000);
            return;
        }
        $.ajax({
            url: './cart/query',
            type: 'get',
            data: {uId: userObj.u_id}
        }).then(function (res) {
            //开始渲染内容
            let goodList = res.data;
            //遍历数组
            let strHtml = ``;
            [...goodList].forEach(function (el) {
                let c_price = parseFloat(el.c_price).toFixed(2);
                let c_total = parseFloat(el.c_total).toFixed(2);
                let checked = "";
                if (el.c_desc === '1') {
                    checked = "checked";
                }
                strHtml += `<li data-cid=${el.c_id}>
                        <div class="goods clearFix">
                            <div class="col col1">
                                <input type="checkbox" class="selectItem" ${checked}>
                            </div>
                            <div class="col col2">
                                <a href="javascript:" class="goodsImg">
                                    <img src="${el.c_img}" alt="">
                                </a>
                                <div class="txtWrap">
                                    <h3 class="goodTlt">
                                        <a href="javascript:" class="goodsName">
                                            ${el.c_name}
                                        </a>
                                    </h3>
                                </div>
                            </div>
                            <div class="col col3">
                                <span>￥<em>${c_price}</em></span>
                            </div>
                            <div class="col col4">
                                <span class="u-setCount clearFix">
                                    <span class="reduce addReduce disabled">-</span>
                                    <input type="text" class="goodsNum" value="${el.c_num}">
                                    <span class="add addReduce">+</span>
                                </span>
                            </div>
                            <div class="col col5">
                                <span class="sumPrice">￥<em>${c_total}</em></span>
                            </div>
                            <div class="col col6">
                                <a href="javascript:" class="delete">
                                    删除
                                </a>
                            </div>
                        </div>
                    </li>`;
            });
            $('.goods-car').html(strHtml);

            //更新网页数据
            update();
            reduceDisabled();
        });
    }

    return {
        renderAside,
        render
    }
})()